package com.shadowtorcher.stdisk.util;

import com.shadowtorcher.stdisk.bean.CdnBean;
import com.shadowtorcher.stdisk.bean.LogicFileBean;
import com.shadowtorcher.stdisk.bean.PhysicsFileBean;
import com.shadowtorcher.stdisk.bean.UserBean;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {
    private MessageDigest messageDigestMd5;
    private MessageDigest messageDigestHash;
    private long fileSize;

    public FileUtil(File file) throws FileNotFoundException {
        fileSize = file.length();
        try {
            messageDigestMd5 = MessageDigest.getInstance("MD5");
            messageDigestHash = MessageDigest.getInstance("SHA-256");

            InputStream inputStream = new FileInputStream(file);

            byte[] buffer = new byte[4096];
            int size;
            while ((size = inputStream.read(buffer)) != -1) {
                messageDigestHash.update(buffer, 0, size);
                messageDigestMd5.update(buffer, 0, size);
            }
            inputStream.close();

        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成下载链接
     *
     * @param logicFile 逻辑文件
     * @param user      用户
     * @return /download/$UUID/$用户名/$时间戳/$校验码/$文件名
     */
    public static String generateDownloadUrl(LogicFileBean logicFile, UserBean user) {
        StringBuilder ans = new StringBuilder("/download/");
        String encryptedDate = encryptDate(new Date());

        ans.append(logicFile.getPhysicsFileID()).append("/");
        ans.append(user.getUserName()).append("/");
        ans.append(encryptedDate).append("/");
        ans.append(getCheckCode(logicFile.getPhysicsFileID(), user.getUserName(), encryptedDate)).append("/");
        ans.append(logicFile.getLogicFileName());
        return StaticUtils.getEncodeUrl(ans.toString());
    }

    private static String getCheckCode(String ID, String UserName, String Date) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            String checkURL = ID + UserName + Date + "Magic String";
            messageDigest.update(checkURL.getBytes());
            String md5String = DatatypeConverter.printHexBinary(messageDigest.digest()).toUpperCase();
            return md5String.substring(0, 4);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    // copy from dragons treasure Until
    private static String encryptDate(Date date) {
        String dateString = new SimpleDateFormat("YYYYMMddHH").format(date);
        int i = Integer.valueOf(dateString, 10);
        return Integer.toString(i, 36).toUpperCase();
    }

    public static boolean deleteFile(PhysicsFileBean physicsFileBean, CdnBean cdnBean) throws IOException {
        String url = "/delete/" + physicsFileBean.getPhysicsFileID();
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(cdnBean.getCdnUrl() + url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("User-Agent", "dragons-treasure-client-0.1");
        urlConnection.connect();
        urlConnection.getResponseCode();
        return urlConnection.getResponseCode() == 200;
    }

    public String getMd5() {
        return DatatypeConverter.printHexBinary(messageDigestMd5.digest()).toUpperCase();
    }

    public String getHash() {
        return DatatypeConverter.printHexBinary(messageDigestHash.digest()).toUpperCase();
    }

    public long getFileSize() {
        return fileSize;
    }
}
